package io;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

/**
 * 处理服务端 channel
 */
public class DiscardServerHandler extends ChannelInboundHandlerAdapter { // (1)

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) { // (2)
        ByteBuf in = (ByteBuf) msg;
        try {
//            String line = in.toString(StandardCharsets.UTF_8);
//             控制台打印
//            System.out.println(line);

            // 原样输出到远端
//            in.writeCharSequence(String.valueOf(System.currentTimeMillis()), StandardCharsets.UTF_8);
            ctx.writeAndFlush(msg);
        } finally {
            /*
             * 丢弃收到的数据
             *
             *  if (msg instanceof ReferenceCounted) {
             *      return ((ReferenceCounted) msg).release();
             *  }
             *  return false;
             */
            ReferenceCountUtil.release(msg);
        }

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)
        // 当出现异常就关闭连接
        cause.printStackTrace();
        ctx.close();
    }
}